package com.niit.gams.utils;

import com.niit.gams.pojo.TreeNode;

import java.util.ArrayList;
import java.util.List;

public class TreeUtil {
  private List<TreeNode> nodeList;

  public TreeUtil(List<TreeNode> nodeList) {
    this.nodeList = nodeList;
  }

  private List<TreeNode> getRootNodes(){
    // 保存所有根节点（所有根节点的数据）
    List<TreeNode> rootNodeList = new ArrayList<>();
    for (TreeNode node:nodeList) {
       if(node.getPId()==0){
          rootNodeList.add(node);
       }
    }
    return rootNodeList;
  }

  public List<TreeNode> buildTree(){
    List<TreeNode> pNodes = new ArrayList<>();
    for (TreeNode pNode:getRootNodes()) {
       pNode = buildChildTree(pNode);
      pNodes.add(pNode);
    }
    return pNodes;
  }



  private TreeNode buildChildTree(TreeNode pNode){
    List<TreeNode> childTree = new ArrayList<TreeNode>();
    for (TreeNode cNode:nodeList) {
       if(cNode.getPId()==pNode.getId()){
         childTree.add(buildChildTree(cNode));
       }
    }
    pNode.setChildren(childTree);
    return pNode;
  }

  public static void main(String[] args) {
    // 模拟测试数据（通常为数据库的查询结果）
//    List<TreeNode> treeNodeList = new ArrayList<>();
//    treeNodeList.add(new TreeNode(1,0,"顶级节点A"));
//    treeNodeList.add(new TreeNode(2,0,"顶级节点B"));
//    treeNodeList.add(new TreeNode(3,1,"父节点是A"));
//    treeNodeList.add(new TreeNode(4,2,"父节点是B"));
//    treeNodeList.add(new TreeNode(5,2,"父节点是B"));
//    treeNodeList.add(new TreeNode(6,3,"父节点的ID是3"));
//    treeNodeList.add(new TreeNode(7,6,"父节点的ID是6"));
//    TreeUtil util = new TreeUtil(treeNodeList);
//    System.out.println(util.buildTree());
  }
}
